define(function(require) {
	var $ = require("jquery1.7");
	var backManagerService = require("bean/backManagerService");
	var Confirmbox = require("confirmbox");
	var utils = require("utils");
	var ui = require("ui");
	require("zTree");
	require("ztree-exedit");
	require("ztree-excheck");
	var ctx = utils.constants.ctx;	
	
	var deleteUserList = function(){
		if ($('input[name=items]:checkbox:checked').length <= 0) {
			alert("请选择用户");
			return;
		}
		if(!window.confirm("确定要删除用户信息？")){
			return;
		}
		var array = [];
		$('input[name=items]:checkbox:checked').each(function() {
		    	
			var id = $(this).attr("id").replace("user_", "");
			array.push(id);   
		});
		
		if (array.length != 0) {
			try{
				ui.mask().show("请稍候...");
				backManagerService.userDelete(array);
				backManagerService.userDetailDelete(array);
				ui.mask().hide();
				alert("删除成功");
				window.location.reload();
			} catch (e) {
				ui.mask().hide();
				alert("删除失败:"+e.message);
			}
		} 
	}
	//删除用户列表
	$("#deleteUserList").bind("click", deleteUserList);
	
	$("#user_m_group_d").hover(function(){
		$(this).show();
	}, function(){
		$(this).hide();
	});

	$("#user_m_group_name").bind("click",function(){
		$("#user_m_group_d").show();
	});
	
	//zTree基本设置
	var user_group_setting = {
			
		data : {
			simpleData :{
				enable :true,
				idKey : "id",
				pIdKey : "parentId" 
			}
			
		},
		view : {
			expandSpeed:"",
			selectedMulti: false
			
		},
		edit : {
			enable : false
		},
		callback : { //回调函数  
			beforeClick: beforeClick_user_m_group,
			onClick: afterClick_user_m_group
		}
	};
	
	function beforeClick_user_m_group(treeId, treeNode, clickFlag){
		$("#user_m_group_name").val(treeNode.name);
		$("#user_m_group_name").focus();			
		$("#user_m_group_i").val(treeNode.id);
	}
	
	function afterClick_user_m_group(treeId, treeNode, clickFlag){
		$("#user_m_group_d").hide();
	}
	
	//加载用户组信息
	try{
		var groups = backManagerService.getGroupList(1);
		var grades = backManagerService.getGroupList(2);
		groups = groups.concat(grades);
		$.fn.zTree.init($("#user_m_sortTree"), user_group_setting, groups);
	} catch (e) {
		alert("加载身份失败:"+e.message);
	}
	
	//加载身份信息
	try{
		var userIdentitys = backManagerService.getUserIdentityList();
		var userIdentity_i = $('#user_m_indentify_input').val();
		var c_ops = "<option value=''>所有身份</option>";
		for(var i=0;i<userIdentitys.length;i++) {
			var tmp = "";
			if(userIdentity_i != "" && userIdentity_i == userIdentitys[i].id) {
				tmp = " selected='true' ";
			}
			c_ops += '<option value="' + userIdentitys[i].id + '"' + tmp + '>' + userIdentitys[i].name + '</option>';
		}
		$('#user_m_indentify_s').html(c_ops);
	} catch (e) {
		alert("加载身份失败:"+e.message);
	}
	
	//查询用户
	$("#searchBtn").bind("click",function(){
		var groupId = $("#user_m_group_i").val();
		var groupName = $("#user_m_group_name").val();
		var indentifyId = $("#user_m_indentify_s").val();
		var searchContent = $("#searchInfo").val();
					
		ui.mask().show("请稍候...");
		location.href = ctx+"/back/base/userList?groupId="+groupId+"&groupName="+groupName+"&indentifyId="+indentifyId+"&username="+searchContent;
		
	});
	//角色的分配权限
	var updateRolesCb;
	$(".jw_btn_role").bind("click",function(){
		
		var userId = $(this).attr("user_id").replace("user_", "");
		var groupId = $(this).attr("group_id").replace("user_", "");
		var identityId = $(this).attr("userIdentityId").replace("user_", "");
		var roleIds = $(this).attr("roleIds").replace("user_", "");
		var data = '<div id="user_role_info" style="min-height: 100px;">';
		
		var allRoles;
		var groupRoles;
		roleIds = eval('(' + roleIds + ')');
		try{
			allRoles = backManagerService.loadAllroles();
			groupRoles = backManagerService.getUserGroupRoles(parseInt(groupId));
			var userIdentityRoles = backManagerService.getUserIdentityRoles(identityId);
			groupRoles = groupRoles.concat(userIdentityRoles);
		} catch (e) {
			alert("加载数据失败:" + e.message);
			return;
		}

		for(var i=0;i<allRoles.length;i++) {
			
			var v = 20;
			if(allRoles[i].name != null && allRoles[i].name.length > 6) {
				v = 0;
			}
			var checked = '';
			for(var k=0; k<roleIds.length; k++){
				if(roleIds[k]==allRoles[i].id){
					checked = 'checked="checked"'; 
				}
			}
			var enable = '';
			var title = '';
			var color = '';
			for(var j=0;j<groupRoles.length;j++) {

				if(allRoles[i].id == groupRoles[j].id) {
					
					enable = 'disabled';
					title = 'title="来源组的角色"';
					checked = 'checked="checked"';
					color = 'color:red;';
					break;
				}
			}
			data += '<span ' + title + ' style="' + color + 'overflow: hidden;margin-bottom:' + v + 'px;width: 100px;display: block;float: left;">' 
					+ '<input ' + enable + ' type="checkbox" ' + checked + ' name="user_roles" id="user_role_'
					+ allRoles[i].id + '">' + allRoles[i].name + '</span>';
		}
		data += '</div>'

		if(updateRolesCb == null) {
			updateRolesCb = new Confirmbox({
				
				trigger: '#user_role_confirmbox',
				title: "分配角色<font color='red'>（组内角色不能修改）</font>",
				message: data,
				width : 450,
				onConfirm: function() {
		
					var ch = $('#user_role_info input[name="user_roles"]');
					var newRoleIds = []; //新角色ids
					
					for(var i=0; i<ch.length;i++) {

						if("checked" == ch.eq(i).attr("checked")) {
							var id = parseInt(ch.eq(i).attr("id").replace("user_role_", ""));
							var flag = true;
							for(var j=0;j<groupRoles.length;j++) {
								if(id == groupRoles[j].id) {
									flag = false;
									break;
								}
							}
							if(flag) {
								newRoleIds.push(id);
						    }
						}
					}
					
					try{

						backManagerService.userAllotRole(userId, newRoleIds);
						alert("分配角色成功！");
						this.hide();
						window.location.reload();
					} catch (e) {
						alert("分配角色失败:" + e.message);
						return;
					}
				}
			});
		} else {					
			updateRolesCb.before('show',function() {

		       this.set('message', data);		       
		   });
		}
		updateRolesCb.show();
		/*
		//添加角色选择事件
		$('#user_role_info input[name="user_roles"]').bind("click", function(){

			if(typeof $(this).attr("checked") == "undefined") {
				$(this).attr("checked", "checked");
			} else {
				$(this).removeAttr("checked");
			}
		});*/
	});
	
	//用户的分配权限
	var updateRescourceCb;
	$(".jw_btn_resource").bind("click",function(){
		
		var userId = $(this).attr("user_id").replace("user_", "");
		var data = '<div id="user_resource_tree" class="ztree" style="min-height:160px;"></div>';
		
		var roleResources; //来源于用户的角色权限
		try{
			roleResources = backManagerService.loadUserRolesResources(userId);
		} catch (e) {
			alert("加载数据失败:" + e.message);
			return;
		}
		
		if(updateRescourceCb == null) {
			updateRescourceCb = new Confirmbox({
				
				trigger: '#user_resource_tree',
				title: "用户的权限资源",
				message: data,
				width : 450,
				confirmTpl: '',
		        cancelTpl: '',
				onConfirm: function() {
					/*
					var zTree = $.fn.zTree.getZTreeObj("user_resource_tree");
					var nodes = zTree.getCheckedNodes(true);
					var nodeIds = [];
					for(var i=0; i<nodes.length; i++) {
						var flag = true;
						for(var j=0; j<roleResources.length; j++) {
							if(nodes[i].id == roleResources[j].id){
								flag = false;
								break;
							}
						}
						if(flag) {
							nodeIds.push(nodes[i].id);
						}
					}	
					try {

						backManagerService.userAllotResource(roleId, nodeIds);
				 		alert('分配成功');
				 		window.location.reload();
				 	} catch (e){
						alert('分配失败！<br/>' + e.message);
				 	}*/
				}
			});
		} else {					
			updateRescourceCb.before('show',function() {

		       this.set('message', data);
		   });
		}
		updateRescourceCb.show();
		//zTree基本设置
		var user_resource_setting = {
				
				data : {
					simpleData :{
						enable :true,
						idKey : "id",
						pIdKey : "parentId" 
					}
					
				},
				check: {
					enable: true,
					chkStyle: "checkbox",
					chkDisabled : false
				},
				async : {
					enable : true,
					url : ctx + "/back/base/resource-json", 
					autoParam : ["id","name"]
				},
				
				view : {
					expandSpeed:"",
					selectedMulti: false		
				},
				edit : {
					enable : true,
					showRemoveBtn:false,
					showRenameBtn:false,
					drag: {
						isCopy: false,
						isMove: false
					}
				},
				callback : { //回调函数  
					onAsyncSuccess: function() {
						
						ui.mask().hide();
						var zTree = $.fn.zTree.getZTreeObj("user_resource_tree");

						for(var i=0; i < roleResources.length; i++) {
							var node = zTree.getNodeByParam("id", roleResources[i].id);
							zTree.checkNode(node, true, false);
						}
						var nodes = zTree.getNodes();
						for(var i=0; i < nodes.length; i++) {
							zTree.setChkDisabled(nodes[i], true, true, true);
						}
					}
		        } 
		};
		$.fn.zTree.init($("#user_resource_tree"), user_resource_setting, []);
		ui.mask().show("请稍候...");
	});
	
	//重置用密码
	$(".jw_btn_key_delete").bind("click",function(){
		var userId = $(this).prev().attr("user_id").replace("user_","");
		if(backManagerService.resetPassword(userId)){
			alert("密码重置成功，重置密码为1");
		} else {
			alert("密码重置失败！请刷新页面后再试");
		}
	});
	
	//导入用户
	$.post(ctx + "/back/base/userimportUI",function(data){
		var importCb = new Confirmbox({
			trigger: '#importUser',
			title: "批量导入用户",
			message: data,
			confirmTpl: '<button id="importContinue" style="display:none">继续</button>',
			cancelTpl: '<button id="importFinish" style="display:none">完成</button><button id="importCancel" style="display:none">取消</button>'
		});
		
		importCb.before('show', function() {
			$("#uploadMessage").html("");
			$("#maskDiv").hide();
		});
		
		importCb.on('cancel', function() {
			window.location.reload();
			this.hide();
		});
		
	});
		
    //导出用户
	$("#exportUser").bind("click",function(){
		if(!window.confirm("确定要导出所有用户？")){
			return;
		}
		ui.mask("body").show("请稍候...");
		$.post(ctx+"/back/base/exportUser",function(data){
			ui.mask("body").hide();
			window.open(ctx + data);
		});
	});
	
	var addGroupCb;
	$("#setClassAndGroup").click(function(){
		if ($('input[name=items]:checkbox:checked').length <= 0) {
			alert("请选择用户");
			return;
		}
//		if(!window.confirm("确定要设置用户分组？")){
//			return;
//		}
		var array = [];
		$('input[name=items]:checkbox:checked').each(function() {
		    	
			var id = $(this).attr("id").replace("user_", "");
			array.push(id);   
		});
		
		var data = '<div id="user_group_tree" class="ztree" style="height:200px;overflow-y: scroll;"></div>';
				
		if(addGroupCb == null) {
			addGroupCb = new Confirmbox({
				
				trigger: '#user_group_tree',
				title: "用户的部门或者班级",
				message: data,
				width : 450,
				onConfirm: function() {
					var treeObj = $.fn.zTree.getZTreeObj("user_group_tree");
					var nodes = treeObj.getCheckedNodes(true);
					if(nodes.length == 0) {
						alert("请选择部门或者班级！");
						return;
					}
					var result = backManagerService.setUserGroup(array,nodes[0].id);
					alert(result);
					window.location.reload();
				}
			});
		} else {					
			addGroupCb.before('show',function() {

		       this.set('message', data);
		   });
		}
		addGroupCb.show();
		//zTree基本设置
		var user_resource_setting = {
				
				data : {
					simpleData :{
						enable :true,
						idKey : "id",
						pIdKey : "parentId" 
					}
					
				},
				check: {
					enable: true,
					chkStyle: "radio",
					radioType:"all"
				},
				async : {
					enable : true,
					url :  ctx + "/back/base/group-json?sortId=-1", 
					autoParam : ["id","name"]
				},
				
				view : {
					expandSpeed:"",
					selectedMulti: false		
				},
				edit : {
					enable : true,
					showRemoveBtn:false,
					showRenameBtn:false,
					drag: {
						isCopy: false,
						isMove: false
					}
				},
				callback : { //回调函数  
					onAsyncSuccess: function() {
						
						var zTree = $.fn.zTree.getZTreeObj("user_group_tree");
						var nodes = zTree.getNodes();
						for(var i=0; i < nodes.length; i++) {
							if(nodes[i].sortId == 2 && nodes[i].isParent){
								zTree.setChkDisabled(nodes[i], true);
							}
						}
						ui.mask().hide();
					}
		        } 
		};
		$.fn.zTree.init($("#user_group_tree"), user_resource_setting, []);
		ui.mask().show("请稍候...");
		
	})
	
	
	$("a[id^=socreUpdate_]").bind("dblclick",function(){
		
		var id = $(this).attr("id").replace("socreUpdate_","");
		var score = $(this).html();
		
		var data = '<div><input id="updateValue_' + id + '" value="'+score+'"></div>';
		
		var updateScoreCb = new Confirmbox({
			
			trigger: '',
			title: "修改积分",
			message: data,
			width : 450,
			onConfirm: function() {
				var tempScore = $("#updateValue_"+id).val();
				var reg = /^\+?[1-9][0-9]*$/;
				if(!reg.test(tempScore)){
				    alert("请输入数字!");
				    return ;
				}
				if(tempScore != score) {
					backManagerService.updateUserScore(id,tempScore);
					alert("修改成功！");
				}
				window.location.reload();
			}
		});
		updateScoreCb.show();
		
	})
/**************************************添加和更新用户信息js*****************************************************/

	//添加用户方法
	var userSubmit = function (){
		var userId = $("#user_id").val();
	    var username = $("#user_username").val();
		var	nickname = $("#user_nickname").val();
		var	identityId = $("#user_identity").val();
		var	email = $("#user_email").val();
		var	phone = $("#user_phone").val();
		if(username == ""){
			$("#user_username").trigger("focus");
			$("#user_username").trigger("blur");
			return false;
		}
	 	if(nickname == "" ){
			$("#user_nickname").trigger("focus");
			$("#user_nickname").trigger("blur");
			return false;
		}
	 	var reg1 = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.(?:com|cn)$/;
	 	if(email == "" || !reg1.test(email)){
	 		$("#user_email").trigger("focus");
			$("#user_email").trigger("blur");
			return false;
	 	}

	 	var user = {
	 			id : userId,
    			username : username,
    			nickname : nickname,
    			identityId : identityId,
    			email : email,
    			phoneNumber : phone,
    			approval : 1
    		};
	 	
	 	try {
	 		if (userId == ""){
    	 		backManagerService.userAdd(user);
    	 		alert("111");
    	 		alert('添加成功');
	 		} else {
    	 		backManagerService.userUpdate(user);
		 		alert('修改成功');
	 		}
	 		location.href = ctx+"/back/base/userList";
	 	} catch (e){
	 		alert("3432");
			alert(e.message);
	 	}
	}
	$("#userSubmit").bind("click",userSubmit);

});